﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using WebShop.Contracts;
using WebShop.DAL.Interfaces;
using WebShop.DAL.Repositories;
using WebShop.Infrastructure;
using WebShop.Models;
using WebShop.ViewModels;

namespace WebShop.Controllers
{
    [Authorize]
    [HandleErrors]
    public class ProductsCartController : Controller
    {
        [Dependency]
        public IProductRepository Products { get; set; }

        [Dependency]
        public ISupplierRepository Suppliers { get; set; }

        [Dependency]
        public IUserRepository Users { get; set; }

        [Dependency]
        public ProductsCartRepository ProductsCart { get; set; }

        private const int PAGE_SIZE = 20;

        //
        // GET: /ProductsCart/

        public ViewResult Index()
        {
            ProductsCart cart = ProductsCart.LoadCart(HttpContext);

            List<Product> productsDb = Products.FindList(1, PAGE_SIZE, p => cart.ProductIDs.Contains(p.ProductID), p => p.ProductName);
            List<ProductInCart> products = cart.FillProductsInfo(productsDb);

            ProductsInCart productsInCart = new ProductsInCart(products, true);

            return View(productsInCart);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Exclude = "Product")]List<ProductInCart> products)
        {
            if (ModelState.IsValid)
            {
                ProductsCart cart = ProductsCart.LoadCart(HttpContext);
                cart.UpdateProducts(products);
                ProductsCart.SaveCart(HttpContext, cart);

                return RedirectToAction("Create", "Orders");
            }

            return View();
        }

        public ActionResult Delete(int id)
        {
            if (ModelState.IsValid)
            {
                ProductsCart cart = ProductsCart.LoadCart(HttpContext);
                ProductInCart c = new ProductInCart(id, cart.Products.FirstOrDefault(p => p.ProductID == id).Quantity);
                cart.RemoveProduct(c);
                ProductsCart.SaveCart(HttpContext, cart);
            }

            return RedirectToAction("Index");
        }
    }
}